package com.stt.experiment.trynetty.server;

import com.stt.experiment.trynetty.server.config.ServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class NettyServer implements Runnable{

    private final ServerConfig serverConfig;
    private final ServerChannelInitializer serverChannelInitializer;

    @Autowired
    public NettyServer(ServerConfig serverConfig, ServerChannelInitializer serverChannelInitializer) {
        this.serverConfig = serverConfig;
        this.serverChannelInitializer = serverChannelInitializer;
    }

    @Override
    public void run() {
        String host = serverConfig.getHost();
        int port = serverConfig.getPort();
        // 服务端需要2个线程组，boss处理客户端链接，work进行客户端连接之后的处理
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            // 服务器配置
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(serverChannelInitializer);
            //绑定端口,开始接收进来的连接
            ChannelFuture f = bootstrap.bind(host, port).sync();
            log.info("===========启动成功===========");
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
